//
//  FKBindMobileVC.m
//  WanTao
//
//  Created by Macbook Pro on 2019/3/14.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKBindMobileVC.h"
#import "FKWebViewVC.h"
#import "FKInviteCodeVC.h"

@interface FKBindMobileVC ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *mobileField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;

@property (nonatomic, copy) NSString *tel;

@end

@implementation FKBindMobileVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([self.type isEqualToString:@"1"]) {
        self.title = @"手机号登录";
    } else {
        self.title = @"绑定手机号";
    }
    [self.getCodeBtn setBackgroundImage:[UIImage imageNamed:@"bg_main"] forState:UIControlStateNormal];
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"bg_main"] forState:UIControlStateNormal];
    
    if (@available(iOS 12.0, *)) {
        self.codeField.textContentType = UITextContentTypeOneTimeCode;
    }
    
    [self loadData];
}

- (IBAction)getCodeBtnClicked:(UIButton *)sender
{
    [self.view endEditing:true];
    if (![self.mobileField.text fk_isPureInt] || self.mobileField.text.length != 11) {
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号"];
        return;
    }
    
    sender.enabled = false;
    [self.codeField becomeFirstResponder];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSString *suffix = @"m=Home&c=MsgCode&a=loginSendCode";
    if ([self.type isEqualToString:@"2"]) {
        suffix = @"m=Home&c=MsgCode&a=sendCode";
    }
    param[@"mobile"] = self.mobileField.text;
    [FKHttpTool postWithSuffix:suffix param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"验证码发送成功"];
            [sender fk_startWithTime:59 title:@"重新发送" countDownTitle:@"秒" normalColor:nil countdownColor:nil];
        } else {
            sender.enabled = true;
        }
    } failure:^(NSError *error) {
        sender.enabled = true;
    }];
}

- (IBAction)loginBtnClicked:(UIButton *)sender
{
    [self.view endEditing:true];
    
    if (![self.mobileField.text fk_isPureInt] || (self.mobileField.text.length != 11)) {
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        return;
    }
    if (self.codeField.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:self.codeField.placeholder];
        return;
    }
    if (!self.agreeBtn.isSelected) {
        [SVProgressHUD showInfoWithStatus:@"请选择并同意用户协议"];
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSString *suffix = @"m=Home&c=Login&a=mobileLogin";
    param[@"mobile"] = self.mobileField.text;
    param[@"code"] = self.codeField.text;
    param[@"type"] = @"2";
    if ([self.type isEqualToString:@"2"]) { // 绑定手机号
        suffix = @"m=Home&c=Login&a=bindMobile2";
    }
//    param[@"lat"] = self.codeField.text;
//    param[@"lng"] = self.codeField.text;
    [FKHttpTool postWithSuffix:suffix param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            // 改变tabbar中item的数量
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTabBar" object:nil];
            
            if ([self.type isEqualToString:@"1"]) { // 手机号登录
                // 缓存登录信息的同时
                [FKCacheTool saveLoginInfo:result.data];
                [FKCacheTool saveUserInfo:result.data[@"user_info"]];
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                [FKLoginTool changeRootVC];
//                [self.navigationController dismissViewControllerAnimated:true completion:nil];
            } else { // 绑定手机号
                [SVProgressHUD showSuccessWithStatus:@"手机号绑定成功"];
                
                // 更新手机号的绑定状态
                NSMutableDictionary *cacheLoginInfo = [NSMutableDictionary dictionaryWithDictionary:[FKCacheTool loginInfo]];
                NSMutableDictionary *cacheUserInfo = [NSMutableDictionary dictionaryWithDictionary:cacheLoginInfo[@"user_info"]];
                cacheUserInfo[@"bind_mobile"] = @"1";
                cacheLoginInfo[@"user_info"] = cacheUserInfo;
                [FKCacheTool saveLoginInfo:cacheLoginInfo];
                
                NSDictionary *userInfo = result.data[@"user_info"];
                if ([fkFORMAT(@"%@", userInfo[@"bindInviteCode"]) isEqualToString:@"0"]) { // 没有绑定了邀请码
                    FKInviteCodeVC *vc = [[FKInviteCodeVC alloc] init];
                    fkPushNav(vc);
                } else {
                    [FKLoginTool changeRootVC];
//                    [self.navigationController dismissViewControllerAnimated:true completion:nil];
                }
            }
        }
    } failure:nil];
}

- (IBAction)agreeBtnClicked:(UIButton *)sender
{
    sender.selected = !sender.isSelected;
}

- (IBAction)agreementBtnClicked:(UIButton *)sender
{
    sender.enabled = false;
    [SVProgressHUD show];
    [FKHttpTool postWithSuffix:@"m=Home&c=Login&a=regProtocol" param:nil success:^(FKBaseResult *result) {
        sender.enabled = true;
        if (result.isSuccess) {
            [SVProgressHUD dismiss];
            NSDictionary *regProtocol = result.data[@"regProtocol"];
            FKWebViewVC *vc = [FKWebViewVC webVCWithPath:[NSURL URLWithString:regProtocol[@"url"]] title:@"注册协议"];
            fkPushNav(vc);
        }
    } failure:^(NSError *error) {
        sender.enabled = true;
    }];
}

- (IBAction)contactBtnClicked:(UIButton *)sender
{
    if (self.tel) {
        fk_call(self.tel);
    } else {
        [SVProgressHUD showInfoWithStatus:@"网络连接失败，请稍后再试"];
      
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *finalText = [textField.text stringByAppendingString:string];
    if ([textField isEqual:self.mobileField]) { // 手机号
        if ([finalText fk_isRightPrice]) {
            return true;
        }
        return false;
    } else { // 验证码
        if ([finalText fk_isPureInt] && (finalText.length < 7)) {
            return true;
        }
        return false;
    }
}

#pragma mark - 网络请求
- (void)loadData
{
    [FKHttpTool postWithSuffix:@"m=Home&c=Mine&a=kf_tel" param:nil success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            self.tel = result.data[@"tel"];
        }
    } failure:nil];
}


@end
